﻿var minuteH = 1;
var interval = 0;

$(function() {
    calcDimensions();
    $(window).resize(alignTasks);
    $('#date').change(dateChanged);

    $('#date').calendar({
        parentElement: '#calendarholder',
        dateFormat: '%d.%m.%Y'
    });

    alignTasks();
});

function dateChanged() {
    var newDate = $.parseDate($('#date').val());
    $('#calendarholder td.selected').get(0).calendar.update(new Date(newDate));

    reloadSchedule();
}

function reloadSchedule() {
    var params = $('#scheduleform').serializeArray();
    params[params.length] = { name: 'timestamp', value: new Date() };
    $('#schedule').css('visibility', 'hidden').load(base + 'taskschedule.ivp/day', params, function() { alignTasks(); $('#schedule').css('visibility', 'visible'); });
}

function calcDimensions() {
    interval = $('#interval').val();
    minuteH = $('.taskschedule td').outerHeight() / interval;
}

function alignTasks() {
    $('.task').each(function(i, el) {
        var el = $(el);
        var time = el.attr('time');
        var duration = parseInt(el.attr('duration'), 10);
        el.height(duration * minuteH - 1);
        var tth = $('.taskschedule th:contains("' + time.split(':')[0] + ':00"):first');
        //Если мы найдем ячейку, по которой надо выравнивать, то выровняем по ней
        if (tth.length > 0) el.css('top', tth.position().top + 1 + time.split(':')[1] * minuteH);
        else el.css('top', 0); //Иначе сдаемся и показываем просто сверху
        var th = $('.taskschedule th[schedule="' + el.attr('schedule') + '"]');
        el.css('left', th.position().left + 1).width(th.outerWidth() - 1);
    });
}

function createTask(sid, startdate) {
    var params = '';
    if (parseInt(sid, 10) > 0)
        params = '&startdate=' + startdate + '&scheduleid=' + sid;

    var wnd = openDialog('task.ivp/create?popup=true' + params, '_task');
    wnd.focus();
    return false;
}

function viewTask(id) {
    var wnd = openDialog('task.ivp/view/' + id + '?popup=true','_task');
    wnd.focus();
    return false;
}